<template>
  <div class="stock-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>药品出入库管理</h2>
          <div>
            <el-button type="primary" @click="openStockDialog('in')">入库</el-button>
            <el-button type="warning" @click="openStockDialog('out')">出库</el-button>
          </div>
        </div>
      </template>

      <el-table :data="stockList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="medicineId" label="药品ID"></el-table-column>
        <el-table-column prop="medicineName" label="药品名称"></el-table-column>
        <el-table-column prop="quantity" label="库存数量"></el-table-column>
      </el-table>

      <!-- 移除分页组件 -->
    </el-card>

    <!-- 库存操作对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="operationType === 'in' ? '药品入库' : '药品出库'"
      width="50%"
    >
      <el-form :model="stockForm" label-width="100px">
        <el-form-item label="药品">
          <el-select v-model="stockForm.medicineId" placeholder="请选择药品">
            <el-option
              v-for="item in medicineOptions"
              :key="item.id"
              :label="item.medicineName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="operationType === 'in' ? '入库数量' : '出库数量'">
          <el-input-number v-model="stockForm.quantity" :min="1"></el-input-number>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveStockOperation">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listStock, addStock, updateStock } from '@/api/stock'
import { listMedicine } from '@/api/medicine'

// 库存列表
const stockList = ref([])

// 药品选项
const medicineOptions = ref([])

// 移除分页相关变量
// const currentPage = ref(1)
// const pageSize = ref(10)
// const total = ref(0)

// 对话框显示状态
const dialogVisible = ref(false)

// 操作类型（入库/出库）
const operationType = ref('in')

// 库存表单
const stockForm = reactive({
  medicineId: null,
  quantity: 1,
  remark: '',
})

// 获取库存列表 - 移除分页参数
const getStockList = async () => {
  try {
    // 不传入分页参数，获取所有数据
    const res = await listStock()

    // 获取药品列表
    const medicineRes = await listMedicine()
    const medicineMap = {}
    medicineRes.data.forEach((medicine) => {
      medicineMap[medicine.id] = medicine
    })

    // 合并药品信息
    stockList.value = res.data.map((stock) => {
      const medicine = medicineMap[stock.medicineId] || {}
      return {
        ...stock,
        medicineName: medicine.medicineName || '未知药品',
      }
    })
  } catch (error) {
    console.error('获取库存列表失败', error)
    ElMessage.error('获取库存列表失败')
  }
}

// 获取药品选项
const getMedicineOptions = async () => {
  try {
    const res = await listMedicine()
    medicineOptions.value = res.data || []
  } catch (error) {
    console.error('获取药品列表失败', error)
    ElMessage.error('获取药品列表失败')
  }
}

// 打开库存操作对话框
const openStockDialog = (type) => {
  operationType.value = type

  // 重置表单
  Object.assign(stockForm, {
    medicineId: null,
    quantity: 1,
    remark: '',
  })

  dialogVisible.value = true
}

// 保存库存操作
const saveStockOperation = async () => {
  try {
    if (!stockForm.medicineId) {
      ElMessage.warning('请选择药品')
      return
    }

    // 获取当前库存信息
    const stockRes = await listStock({ medicineId: stockForm.medicineId })
    const currentStock = stockRes.data.find((item) => item.medicineId === stockForm.medicineId)

    if (
      operationType.value === 'out' &&
      (!currentStock || currentStock.quantity < stockForm.quantity)
    ) {
      ElMessage.warning('库存不足，无法出库')
      return
    }

    // 计算新的库存数量
    const newQuantity =
      operationType.value === 'in'
        ? currentStock
          ? currentStock.quantity + stockForm.quantity
          : stockForm.quantity
        : currentStock.quantity - stockForm.quantity

    if (currentStock) {
      // 更新库存
      await updateStock({
        id: currentStock.id,
        medicineId: stockForm.medicineId,
        quantity: newQuantity,
        operationType: operationType.value,
        operationQuantity: stockForm.quantity,
        remark: stockForm.remark,
      })
    } else {
      // 新增库存 - 即使没有该药品的记录也会创建
      await addStock({
        medicineId: stockForm.medicineId,
        quantity: stockForm.quantity, // 直接使用入库数量作为初始库存
        operationType: 'in', // 新增记录时默认为入库操作
        operationQuantity: stockForm.quantity,
        remark: stockForm.remark,
      })
    }

    ElMessage.success(operationType.value === 'in' ? '入库成功' : '出库成功')

    // 关闭对话框
    dialogVisible.value = false

    // 刷新库存列表
    getStockList()
  } catch (error) {
    console.error('操作失败', error)
    ElMessage.error('操作失败')
  }
}

// 移除分页切换方法
// const handlePageChange = (page) => {
//   currentPage.value = page
//   getStockList()
// }

// 初始化
onMounted(() => {
  getStockList()
  getMedicineOptions()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
